package com.example.exjnidemo.exbluetooth01.a;

import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.exjnidemo.exbluetooth01.R;

import java.lang.ref.WeakReference;
import java.util.List;

public class FindBluetoothAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    /*数据源*/
    private List<BluetoothDevice> list;
    /*弱引用*/
    private WeakReference<Context> weakReference ;

    public FindBluetoothAdapter(List<BluetoothDevice> list,Context context) {
        weakReference = new WeakReference<Context>(context);
        this.list = list;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new FindBluetoothAdapter.MyViewHolder(LayoutInflater.from(weakReference.get())
                .inflate(R.layout.item_view, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {
        if (list.size() > 0) {
            BluetoothDevice device = list.get(position);


            TextView tv_text = holder.itemView.findViewById(R.id.tv_text);
            tv_text.setText(list.get(position).getName());


            TextView tv_bondState = holder.itemView.findViewById(R.id.tv_bondState);
            switch (device.getBondState()){
                case BluetoothDevice.BOND_NONE:
                    tv_bondState.setText("未连接");
                    break;
                case BluetoothDevice.BOND_BONDING:
                    tv_bondState.setText("正在连接");
                    break;
                case BluetoothDevice.BOND_BONDED:
                    tv_bondState.setText("已连接");
                    break;

                default:{
                    tv_bondState.setText("未连接");
                    break;
                }
            }


            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (onItemClickListener!=null)
                        onItemClickListener.onClick(list.get(position));
                }
            });
        }
    }


    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
        }
    }


    public interface OnItemClickListener{
        void onClick(BluetoothDevice device) ;
    }


    OnItemClickListener  onItemClickListener ;
    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }
}
